/**
 * 通用JavaScript功能
 */

// 全局配置
window.APP_CONFIG = {
    API_BASE_URL: '',
    MAX_FILE_SIZE: 50 * 1024 * 1024, // 50MB
    ALLOWED_IMAGE_TYPES: ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/tiff', 'image/webp'],
    ALLOWED_JSON_TYPES: ['application/json']
};

// 工具函数
window.Utils = {
    /**
     * 显示加载遮罩
     */
    showLoading: function(message = '加载中...') {
        let overlay = document.getElementById('loadingOverlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'loadingOverlay';
            overlay.className = 'loading-overlay';
            overlay.innerHTML = `
                <div class="loading-spinner">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <div class="mt-2">${message}</div>
                </div>
            `;
            document.body.appendChild(overlay);
        } else {
            overlay.querySelector('.mt-2').textContent = message;
        }
        overlay.style.display = 'flex';
    },

    /**
     * 隐藏加载遮罩
     */
    hideLoading: function() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.style.display = 'none';
        }
    },

    /**
     * 显示成功消息
     */
    showSuccess: function(message) {
        this.showAlert(message, 'success');
    },

    /**
     * 显示错误消息
     */
    showError: function(message) {
        this.showAlert(message, 'danger');
    },

    /**
     * 显示警告消息
     */
    showWarning: function(message) {
        this.showAlert(message, 'warning');
    },

    /**
     * 显示信息消息
     */
    showInfo: function(message) {
        this.showAlert(message, 'info');
    },

    /**
     * 显示警告框
     */
    showAlert: function(message, type = 'info') {
        const alertId = 'alert-' + Date.now();
        const alertHtml = `
            <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        let container = document.querySelector('.alert-container');
        if (!container) {
            container = document.createElement('div');
            container.className = 'alert-container position-fixed top-0 end-0 p-3';
            container.style.zIndex = '9999';
            document.body.appendChild(container);
        }
        
        container.insertAdjacentHTML('beforeend', alertHtml);
        
        // 自动移除警告框
        setTimeout(() => {
            const alertElement = document.getElementById(alertId);
            if (alertElement) {
                alertElement.remove();
            }
        }, 5000);
    },

    /**
     * 确认对话框
     */
    confirm: function(message, callback) {
        if (confirm(message)) {
            callback();
        }
    },

    /**
     * 格式化文件大小
     */
    formatFileSize: function(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    /**
     * 检查文件类型
     */
    isValidImageFile: function(file) {
        return APP_CONFIG.ALLOWED_IMAGE_TYPES.includes(file.type);
    },

    /**
     * 检查JSON文件类型
     */
    isValidJsonFile: function(file) {
        return APP_CONFIG.ALLOWED_JSON_TYPES.includes(file.type) || file.name.toLowerCase().endsWith('.json');
    },

    /**
     * 检查文件大小
     */
    isValidFileSize: function(file) {
        return file.size <= APP_CONFIG.MAX_FILE_SIZE;
    },

    /**
     * 防抖函数
     */
    debounce: function(func, wait, immediate) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                timeout = null;
                if (!immediate) func(...args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func(...args);
        };
    },

    /**
     * 节流函数
     */
    throttle: function(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    /**
     * 深拷贝对象
     */
    deepCopy: function(obj) {
        return JSON.parse(JSON.stringify(obj));
    },

    /**
     * 生成UUID
     */
    generateUUID: function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },

    /**
     * 格式化日期
     */
    formatDate: function(date, format = 'YYYY-MM-DD HH:mm:ss') {
        if (!(date instanceof Date)) {
            date = new Date(date);
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    }
};

// AJAX请求封装
window.Ajax = {
    /**
     * GET请求
     */
    get: function(url, data = {}) {
        return this.request('GET', url, data);
    },

    /**
     * POST请求
     */
    post: function(url, data = {}) {
        return this.request('POST', url, data);
    },

    /**
     * PUT请求
     */
    put: function(url, data = {}) {
        return this.request('PUT', url, data);
    },

    /**
     * DELETE请求
     */
    delete: function(url, data = {}) {
        return this.request('DELETE', url, data);
    },

    /**
     * 通用请求方法
     */
    request: function(method, url, data = {}) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            
            // 设置请求
            if (method === 'GET' && Object.keys(data).length > 0) {
                const params = new URLSearchParams(data).toString();
                url += (url.includes('?') ? '&' : '?') + params;
                xhr.open(method, url);
            } else {
                xhr.open(method, url);
            }
            
            // 设置请求头
            if (method !== 'GET') {
                if (data instanceof FormData) {
                    // FormData会自动设置Content-Type
                } else {
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    data = JSON.stringify(data);
                }
            }
            
            // 设置响应处理
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        resolve(response);
                    } catch (e) {
                        resolve(xhr.responseText);
                    }
                } else {
                    try {
                        const error = JSON.parse(xhr.responseText);
                        reject(error);
                    } catch (e) {
                        reject({ error: xhr.statusText });
                    }
                }
            };
            
            xhr.onerror = function() {
                reject({ error: '网络请求失败' });
            };
            
            // 发送请求
            xhr.send(data);
        });
    },

    /**
     * 上传文件
     */
    upload: function(url, file, progressCallback = null) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('file', file);
            
            const xhr = new XMLHttpRequest();
            
            // 上传进度
            if (progressCallback) {
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percentComplete = (e.loaded / e.total) * 100;
                        progressCallback(percentComplete);
                    }
                });
            }
            
            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        resolve(response);
                    } catch (e) {
                        resolve(xhr.responseText);
                    }
                } else {
                    try {
                        const error = JSON.parse(xhr.responseText);
                        reject(error);
                    } catch (e) {
                        reject({ error: xhr.statusText });
                    }
                }
            };
            
            xhr.onerror = function() {
                reject({ error: '上传失败' });
            };
            
            xhr.open('POST', url);
            xhr.send(formData);
        });
    }
};

// DOM就绪后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化Bootstrap工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 初始化Bootstrap弹出框
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function(popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });
    
    // 自动关闭警告框
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert:not(.alert-permanent)');
        alerts.forEach(function(alert) {
            try {
                const bsAlert = new bootstrap.Alert(alert);
                if (bsAlert) {
                    setTimeout(() => {
                        try {
                            bsAlert.close();
                        } catch (e) {
                            // 忽略错误
                        }
                    }, 5000);
                }
            } catch (e) {
                // 忽略初始化错误
            }
        });
    }, 100);
});

// 全局错误处理
window.addEventListener('error', function(e) {
    if (e.error) {
        console.error('全局错误:', e.error);
    }
    // 防止错误传播
    e.preventDefault();
});

window.addEventListener('unhandledrejection', function(e) {
    console.error('未处理的Promise拒绝:', e.reason);
    // 防止错误传播
    e.preventDefault();
});

// 导出到全局
window.APP_UTILS = Utils;
window.APP_AJAX = Ajax;
